//
//  AppDelegate.swift
//  01-微博项目搭建
//
//  Created by Adolph on 15/5/14.
//  Copyright (c) 2015年 Adolph. All rights reserved.
//

import UIKit

var sharedUserAccount = UserAccount.loadUserAccount()
let showMainNotification = "WBShowMainInterfaceNotification"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
       
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        self.window?.makeKeyAndVisible()
        
        // 从沙盒加载 token，因为 token 使用非常频繁，味了避免每次都重复加载
        println("userAccount -->" + "\(sharedUserAccount)")
        
        // 设置导航栏外观（一经设置，全局有效，外观设置要尽量的早）
        // 以前的商业代码中，appDelegate 中会设置大量的外观代码
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        ///显示主界面的通知
        
        //注册通知,发布通知的同时，传递要切换的 storyBoard 名称
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: showMainNotification, object: nil)
        
        
        showMainInterface()

      return true
    }
    
     /// 所有根视图控制器的切换工作统一管理
    func switchRootViewController(n: NSNotification) {
        println(n)
       switchStoryBoard(n.object as! String)
     }
    
    ///显示主界面
    private func showMainInterface() {
        var sbName = "Main"
        //判断是否登入
        if sharedUserAccount != nil {
            if isNewUpdate() {
             sbName = "NewFeature"
            } else {
               sbName = "Welecome"
            }
        }
        switchStoryBoard(sbName)
    }
    
    ///切换 widow 显示的 StoryBoard
    private func switchStoryBoard(sbName: String) {
    
    let sb = UIStoryboard(name: sbName, bundle: nil)
//    println(window)
    self.window?.rootViewController = sb.instantiateInitialViewController() as? UIViewController
    }
    
    ///检查版本更新
    private func isNewUpdate() -> Bool {
        let versionKey = "versinKey"
        
        //取得当前app版本
        let currentVerSion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let versionValue = NSNumberFormatter().numberFromString(currentVerSion)?.doubleValue ?? 0.0
        
        //取得沙盒版本
        let defaults = NSUserDefaults.standardUserDefaults()
        let sandboxVersion = defaults.doubleForKey(versionKey)
        
        //将新的版本写入到沙盒
        defaults.setDouble(versionValue, forKey: versionKey)
        //立即同步
        defaults.synchronize()
        println(NSHomeDirectory())

        return versionValue > sandboxVersion
        
    }
}

